<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <div class="max-w-[1440px] mx-auto bg-white rounded-lg shadow-sm">
      <!-- 头部 -->
      <div class="flex justify-between items-center p-6 border-b">
        <h1 class="text-2xl font-medium">消息管理</h1>
        <div class="flex gap-4">
          <el-button type="primary" :icon="Refresh" @click="refreshData">
            刷新
          </el-button>
        </div>
      </div>

      <!-- 搜索区 -->
      <div class="p-6 border-b">
        <div class="flex gap-4 flex-wrap">
          <div style="display: flex">
            <el-select
              v-model="searchForm.status"
              placeholder="处理状态"
              class="w-[150px]"
              style="width: 300px"
            >
              <el-option label="全部" value="" />
              <el-option label="已处理" value="handled" />
              <el-option label="未处理" value="unhandled" />
            </el-select>
          </div>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="RefreshLeft" @click="resetSearch">重置</el-button>
        </div>
      </div>

      <!-- 表格区 -->
      <div class="p-6">
        <el-table
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa' }"
          v-loading="loading"
        >
          <el-table-column prop="userName" label="用户ID" width="120" />
          <el-table-column prop="info" label="反馈内容" min-width="200">
            <template #default="{ row }">
              <el-tooltip :content="row.info" placement="top" :show-after="500">
                <span class="block truncate">{{ row.info }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="处理状态" width="100">
            <template #default="{ row }">
              <!-- 使用 === 进行严格比较，并修正拼写错误 -->
              <el-tag :type="row.handleUser === '-1' ? 'danger' : 'uccess'">
                {{ row.handleUser === "-1" ? "未处理" : "已处理" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="handleUser" label="处理人" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="updateTime" label="更新时间" width="180" />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.handleUser === '-1'"
                type="primary"
                link
                @click="handleMessage(row)"
                >处理</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="flex justify-end mt-4">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 处理弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="处理反馈"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="space-y-4">
        <div class="bg-gray-50 p-4 rounded">
          <div class="text-gray-500 mb-2">反馈内容：</div>
          <div>{{ currentMessage?.info }}</div>
        </div>
        <el-form :model="handleForm" label-width="80px">
          <el-form-item label="处理备注">
            <el-input
              v-model="handleForm.remark"
              type="textarea"
              rows="4"
              placeholder="请输入处理备注"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmHandle"
            :loading="submitting"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { Search, Refresh, RefreshLeft } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { MessageControllerService } from "../../../backendapi";
import { useStore } from "vuex";
const store = useStore();
interface Message {
  id: number;
  userName: string;
  info: string;
  handleUser: string;
  createTime: string;
  updateTime: string;
}

// 搜索表单
const searchForm = reactive({
  userName: "",
  status: "",
  dateRange: [] as string[],
});

// 处理表单
const handleForm = reactive({
  remark: "",
});

// 表格数据
const tableData = ref<Message[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const currentMessage = ref<Message | null>(null);
const submitting = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 刷新数据
const refreshData = async () => {
  loading.value = true;
  try {
    const response = await MessageControllerService.findAllUsingGet();
    tableData.value = response.data || [];
    total.value = response.total || 0;
    ElMessage.success("数据已更新");
  } catch (error) {
    ElMessage.error("数据更新失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = async () => {
  loading.value = true;
  try {
    let name = searchForm.status;
    let pageNum = currentPage.value;
    let pageSizeVal = pageSize.value;
    const response = await MessageControllerService.findPageUsingGet(
      pageNum,
      pageSizeVal,
      name
    );
    console.log(response.data);
    tableData.value = response.data.records || [];
    total.value = response.total || 0;
    console.log(response);
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error("搜索失败");
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  searchForm.userName = "";
  searchForm.status = "";
  searchForm.dateRange = [];
  handleSearch();
};

// 处理消息
const handleMessage = (row: Message) => {
  currentMessage.value = row;
  handleForm.remark = "";
  dialogVisible.value = true;
};

// 确认处理
const confirmHandle = async () => {
  if (!handleForm.remark.trim()) {
    ElMessage.warning("请输入处理备注");
    return;
  }
  submitting.value = true;
  try {
    const id = currentMessage.value?.id;
    const userId = store.state.user?.loginUser?.id;
    const adminResponse = handleForm.remark;
    console.log("adminResponse:", adminResponse);
    console.log("id:", id);
    console.log("userId:", userId);
    const response = await MessageControllerService.handleUsingGet(
      adminResponse,
      id || 0,
      userId
    );
    console.log(response.code);
    if (response.code === "200") {
      dialogVisible.value = false;
      await refreshData();
      ElMessage.success("处理成功");
    } else {
      ElMessage.error("处理失败");
    }
  } catch (error) {
    ElMessage.error("处理失败");
  } finally {
    submitting.value = false;
  }
};

// 分页
const handleSizeChange = async (val: number) => {
  pageSize.value = val;
  await handleSearch();
};

const handleCurrentChange = async (val: number) => {
  currentPage.value = val;
  await handleSearch();
};

// 初始化数据
refreshData();
</script>

<style scoped>
.el-table :deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}
</style>
